/*
 * Copyright (c) 2015. For Intelligent Group.
 */

package com.intelligent.ispc.web.controller;

import com.intelligent.ispc.common.mapper.JsonMapper;
import com.intelligent.ispc.common.utils.StringUtils;
import com.intelligent.ispc.common.web.Servlets;
import com.intelligent.ispc.core.dto.*;
import com.intelligent.ispc.core.service.*;
import com.intelligent.ispc.utils.SystemConfig;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletRequest;

/**
 * Created by Peter.Li on 2015/10/10.
 */

@Controller
@RequestMapping(value = "/report")
public class ReportController {

    @Autowired
    private ReportService reportService;

    @Autowired
    private SystemConfig systemConfig;

    protected JsonMapper mapper = JsonMapper.nonDefaultMapper();

    @RequestMapping(value = "/snView/{type}", method = RequestMethod.GET)
    public String querySN(Model model, @PathVariable("type") String type, ServletRequest request) {

        Map<String, Object> searchParam = Servlets.getParametersStartingWith(request, "search_");
        Page<TestDataExDto> testDataExDtoPage = reportService.searchSerialNumber(searchParam, null);
        List<TestDataExDto> testDataExDtoList = testDataExDtoPage.getContent();
        JRDataSource jrDataSource = new JRBeanCollectionDataSource(testDataExDtoList);

        Map<String, Object> parameterMap = getParameters(searchParam);
        parameterMap.put("total", testDataExDtoList.size());

        model.addAttribute("url", "/WEB-INF/report/history_sn.jasper");
        model.addAttribute("format", type);
        model.addAttribute("parameters", parameterMap);
        model.addAttribute("jrMainDataSource", jrDataSource);

        return "history_reportView";
    }

    @RequestMapping(value = "/stationView/{type}", method = RequestMethod.GET)
    public String queryStation(Model model, @PathVariable("type") String type, ServletRequest request) {

        Map<String, Object> searchParam = Servlets.getParametersStartingWith(request, "search_");
        Page<TestDataExDto> testDataExDtoPage = reportService.searchSerialNumber(searchParam, null);
        List<TestDataExDto> testDataDtoList = testDataExDtoPage.getContent();
        JRDataSource jrDataSource = new JRBeanCollectionDataSource(testDataDtoList);

        List<DUTAttributeDto> dutAttributeDtoList = reportService.searchAttributes(searchParam);
        JRDataSource jrDataSourceAttr = new JRBeanCollectionDataSource(dutAttributeDtoList);

        Map<String, Object> parameterMap = getParameters(searchParam);
        parameterMap.put("total", testDataDtoList.size());

        model.addAttribute("url", "/WEB-INF/report/history_station.jasper");
        model.addAttribute("format", type);
        model.addAttribute("parameters", parameterMap);
        model.addAttribute("jrMainDataSource", jrDataSource);
        model.addAttribute("jrAttrDataSource", jrDataSourceAttr);

        return "history_reportView";
    }

    @RequestMapping(value = "/testItemView/{type}", method = RequestMethod.GET)
    public String queryTestItem(Model model, @PathVariable("type") String type, ServletRequest request) {

        Map<String, Object> searchParam = Servlets.getParametersStartingWith(request, "search_");
        List<TestItemDto> testItemDtoList = reportService.searchTestItem(searchParam);
        Map<String, Object> parameterMap = getParameters(searchParam);
        parameterMap.put("total", testItemDtoList.size());

        JRDataSource jrDataSource = new JRBeanCollectionDataSource(testItemDtoList);

        model.addAttribute("url", "/WEB-INF/report/history_testItem.jasper");
        model.addAttribute("format", type);
        model.addAttribute("parameters", parameterMap);
        model.addAttribute("jrMainDataSource", jrDataSource);

        return "history_reportView";
    }

    @RequestMapping(value = "/yieldView/{type}", method = RequestMethod.GET)
    public String queryYield(Model model, @PathVariable("type") String type, ServletRequest request) {

        Map<String, Object> searchParam = Servlets.getParametersStartingWith(request, "search_");
        List<YieldDto> yieldDtoList = reportService.searchYield(searchParam);
        Map<String, Object> parameterMap = getParameters(searchParam);
        parameterMap.put("total", yieldDtoList.size());

        JRDataSource jrDataSource = new JRBeanCollectionDataSource(yieldDtoList);

        model.addAttribute("url", "/WEB-INF/report/yield_show.jasper");
        model.addAttribute("format", type);
        model.addAttribute("parameters", parameterMap);
        model.addAttribute("jrMainDataSource", jrDataSource);

        return "history_reportView";
    }

    @RequestMapping(value = "/yieldViewHistory/{type}", method = RequestMethod.GET)
     public String queryYieldHistory(Model model, @PathVariable("type") String type, ServletRequest request) {

        Map<String, Object> searchParam = Servlets.getParametersStartingWith(request, "search_");
        Page<TestDataExDto> pageable = reportService.searchYieldSerialNumber(searchParam, null);
        List<TestDataExDto> testDataExDtoList = pageable.getContent();

        Map<String, Object> parameterMap = getParameters(searchParam);
        parameterMap.put("total", testDataExDtoList.size());

        JRDataSource jrDataSource = new JRBeanCollectionDataSource(testDataExDtoList);

        model.addAttribute("url", "/WEB-INF/report/history_sn.jasper");
        model.addAttribute("format", type);
        model.addAttribute("parameters", parameterMap);
        model.addAttribute("jrMainDataSource", jrDataSource);

        return "history_reportView";
    }

    @RequestMapping(value = "/yieldViewTestItem/{type}", method = RequestMethod.GET)
    public String queryYieldTestItem(Model model, @PathVariable("type") String type, ServletRequest request) {

        Map<String, Object> searchParam = Servlets.getParametersStartingWith(request, "search_");
        List<TestItemDto> testItemDtoList = reportService.searchTestItem(searchParam);

        List<DUTAttributeDto> dutAttributeDtoList = reportService.searchAttributes(searchParam);
        JRDataSource jrDataSourceAttr = new JRBeanCollectionDataSource(dutAttributeDtoList);

        Map<String, Object> parameterMap = getParameters(searchParam);
        parameterMap.put("total", testItemDtoList.size());

        JRDataSource jrDataSource = new JRBeanCollectionDataSource(testItemDtoList);

        model.addAttribute("url", "/WEB-INF/report/yield_testItem.jasper");
        model.addAttribute("format", type);
        model.addAttribute("parameters", parameterMap);
        model.addAttribute("jrMainDataSource", jrDataSource);
        model.addAttribute("jrAttrDataSource", jrDataSourceAttr);

        return "history_reportView";
    }

    private Map<String, Object> getParameters(Map<String, Object> searchParam) {

        Map<String, Object> map = new HashMap<String, Object>();
        StringBuilder str = new StringBuilder();

        DateTimeFormatter format = DateTimeFormat.forPattern(systemConfig.getDateFormat());
        String date = DateTime.now().toString(format);
        StringBuilder stationId = new StringBuilder();
        StringBuilder slotNo = new StringBuilder();

        if (searchParam.containsKey("EQ_stationIdOrSlotNo")) {
            List<StationDto> stationDtoList = mapper.fromJson((String) searchParam.get("EQ_stationIdOrSlotNo"), mapper.contructCollectionType(List.class, StationDto.class));
            if (stationDtoList != null && !stationDtoList.isEmpty()) {
                for (int i = 0; i < stationDtoList.size(); i++) {
                    if (StringUtils.isNotBlank(stationDtoList.get(i).getStationId())) {
                        stationId.append(stationDtoList.get(i).getStationId()).append(", ");
                    }
                    if (stationDtoList.get(i).getSlotNos() != null && !stationDtoList.get(i).getSlotNos().isEmpty()) {
                        for (String slot : stationDtoList.get(i).getSlotNos()) {
                            slotNo.append(stationDtoList.get(i).getStationId()).append("-").append(slot).append(", ");
                        }
                    }
                }
            }
        }

        if (searchParam.containsKey("EQ_projectName") && searchParam.get("EQ_projectName") != null) {
            str.append("Project Name:" + searchParam.get("EQ_projectName") + "    ");
        }

       /* if (searchParam.containsKey("EQ_slotNo")&& searchParam.get("EQ_slotNo") != null) {
            str.append("Slot No:" + searchParam.get("EQ_slotNo") + "    ");
        }*/

        if (searchParam.containsKey("EQ_serialNumber") && searchParam.get("EQ_serialNumber") != null) {
            str.append("Serial Number:" + searchParam.get("EQ_serialNumber") + "    ");
        }

        if (searchParam.containsKey("GTE_startTime") && searchParam.get("GTE_startTime") != null) {
            str.append("Start Time:" + searchParam.get("GTE_startTime") + "    ");
        }

        if (searchParam.containsKey("LTE_stopTime") && searchParam.get("LTE_stopTime") != null) {
            str.append("Stop Time:" + searchParam.get("LTE_stopTime") + "    ");
        }

        if (searchParam.containsKey("serialNumber")) {
            str.append("Serial Number:" + searchParam.get("serialNumber") + "    ");
        }

        if (StringUtils.isNotBlank(stationId)) {

            str.append("Station Name:" + stationId.substring(0, stationId.length()-2) + "     ");
        }

        if (StringUtils.isNotBlank(slotNo)) {
            str.append("Slot No:" + slotNo.substring(0, slotNo.length()-2) + "    ");
        }

        if (searchParam.containsKey("EQ_type") && searchParam.get("EQ_type") != null) {
            str.append("Type:" + searchParam.get("EQ_type") + "     ");
        }
        map.put("time", date);
        map.put("params", str);

        return map;
    }
}

